<script lang="ts" setup>
import { FormInstance, FormRules } from 'element-plus';
import zhCn from 'element-plus/lib/locale/lang/zh-cn';
import { createPermission, getPermissionTree, updatePermission } from '@/api';
import { KeyValue, Menu } from '@/model';
import { errorNotice } from '@/libs/utils';
import IconInfo from '@/model/common/iconInfo';

const props = defineProps<{
  // 是否打开弹出层
  visible: boolean;
  // 什么动作触发的弹窗？create：新增；update：编辑
  type: string;
  // 当前被点击的权限行，用作编辑，或新增子权限
  currentRow: Menu | undefined;
}>();

const emits = defineEmits(['closeDialog', 'submitted']);

// 预定义的颜色
const predefineColors = ref<Array<string>>([
  '#22c3aa',
  '#0e9ea3',
  '#f56c6c',
  '#ff4500',
  '#ff8c00',
  '#ffd700',
  '#90ee90',
  '#00ced1',
  '#1e90ff',
  '#c71585',
  '#666666',
  '#ff770f',
  '#1a1a1a',
  '#80d1c8',
  '#ffd4a9',
  '#002ea6',
  '#ff8000',
  '#7977c4',
  '#c8b3a0',
  '#a0c179',
  '#ffee96',
  '#d0000f',
  '#ffe76f',
]);
// 图标列表
const iconList = ref<Array<IconInfo>>([
  {
    group: '系统',
    iconList: [
      ['Plus', 'Minus', 'CirclePlus', 'Search', 'Female', 'Male'],
      ['Aim', 'House', 'FullScreen', 'Loading', 'Link', 'Service'],
      ['Pointer', 'Star', 'Notification', 'Connection', 'ChatDotRound', 'Setting'],
    ],
  },
  {
    group: '方向',
    iconList: [
      [
        'ArrowLeft',
        'ArrowUp',
        'ArrowRight',
        'ArrowDown',
        'ArrowLeftBold',
        'ArrowUpBold',
      ],
    ],
  },
]);
const dialogHeight = ref<string>('');
const menuList = ref<Array<KeyValue>>([]);
const form = reactive<Menu>({});
const formRef = ref<FormInstance>();

const permissionTree = ref<Array<Menu>>([]);
const PermissionProps = { label: 'name', children: 'children' };

const rootDisabled = ref<boolean>(false);

const rules = reactive<FormRules>({
  name: [{ required: true, message: '请输入权限名称', trigger: 'blur' }],
  parentId: [{ required: true, message: '请选择父节点', trigger: 'blur' }],
  type: [{ required: true, message: '请选择权限类型', trigger: 'blur' }],
  // url: [{ required: true, message: '请输入权限路径', trigger: 'blur' }],
  enabled: [{ required: true, message: '请选择是否启用', trigger: 'blur' }],
});

/**
 * 当点击icon选择时
 * @param icon 选中的icon名称
 */
const onSelectIcon = (icon: string) => {
  form.iconName = icon;
};

/**
 * 关闭弹窗，更新默认值
 */
const onClose = () => {
  emits('closeDialog', false, undefined);
  if (!formRef || !formRef.value) {
    return;
  }
  formRef.value.resetFields();
};

/**
 * 新增或编辑提交
 */
const onSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate((valid, fields) => {
    if (valid) {
      if (props.type === 'update') {
        updatePermission(form).then(() => {
          emits('submitted', form);
        });
      } else {
        createPermission(form).then(() => {
          emits('submitted', form);
        });
      }
    } else {
      errorNotice(fields);
    }
  });
};

/**
 * 计算滚动条高度
 */
const calcScrollbarHeight = () => {
  dialogHeight.value = `${window.innerHeight * 0.5}px`;
};

/**
 * 当弹出层被打开时触发
 */
const onOpen = () => {
  calcScrollbarHeight();
  menuList.value.length = 0;
  form.iconColor = '#666666';
  form.enabled = true;
  form.weight = 0;
  // 编辑
  if (props.type === 'update') {
    form.id = props.currentRow!.id;
    form.parentId = props.currentRow!.parentId;
    form.name = props.currentRow!.name;
    form.type = props.currentRow!.type;
    form.iconName = props.currentRow!.iconName;
    form.iconColor = props.currentRow!.iconColor;
    form.weight = props.currentRow!.weight;
    form.url = props.currentRow!.url;
    form.description = props.currentRow!.description;
    form.enabled = props.currentRow!.enabled;
  }
  // 新增-已选中父节点
  else if (props.currentRow) {
    rootDisabled.value = true;
    form.parentId = props.currentRow.id;
    form.id = '';
  }
  // 新增-未选中父节点，即新增根节点
  else {
    rootDisabled.value = false;
    form.parentId = '0';
    form.id = '';
  }
  getPermissionTree().then((res: Array<Menu>) => {
    const root = {
      id: '0',
      parentId: '-1',
      name: '根节点',
      children: res,
      hasChildren: true,
    } as Menu;
    permissionTree.value = new Array(root);
  });
};
</script>

<template>
  <el-dialog
    :model-value="visible"
    :show-close="false"
    @closed="onClose"
    width="60%"
    @open="onOpen"
    :close-on-click-modal="false"
  >
    <template #header>
      <div class="form-header">
        <span class="title">{{ type === 'update' ? '编辑' : '新增' }}</span>
        <div>
          <el-tooltip content="确认" placement="top" effect="light" :show-after="500">
            <el-button class="btn-confirm" circle @click="onSubmit()">
              <el-icon><i-ep-check /></el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip content="取消" placement="top" effect="light" :show-after="500">
            <el-button class="btn-cancel" circle @click.stop="onClose()">
              <el-icon><i-ep-close /></el-icon>
            </el-button>
          </el-tooltip>
        </div>
      </div>
    </template>
    <el-scrollbar :height="dialogHeight" ref="scrollbarRef">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        class="form"
        size="large"
        :show-message="false"
      >
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="父节点" prop="parentId">
              <el-tree-select
                placeholder=" "
                class="form-input"
                node-key="id"
                v-model="form.parentId"
                :data="permissionTree"
                :props="PermissionProps"
                check-strictly
                highlight-current
                default-expand-all
                filterable
                :disabled="rootDisabled"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" class="form-input" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="类型" prop="type">
              <!--使用空格去掉placeholder的默认值-->
              <el-select placeholder=" " v-model="form.type" class="form-input">
                <el-option label="菜单" :value="1" />
                <el-option label="按钮" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="图标" prop="iconName">
              <el-popover
                placement="bottom"
                :width="400"
                trigger="click"
                :hide-after="0"
              >
                <template #reference>
                  <el-input v-model="form.iconName" class="form-input">
                    <template #suffix>
                      <el-icon size="24px" color="#606266">
                        <component :is="form.iconName" />
                      </el-icon>
                    </template>
                  </el-input>
                </template>
                <el-scrollbar height="300px">
                  <div style="width: 100%; height: 500px; min-height: 300px">
                    <template v-for="item in iconList" :key="item.group">
                      <div class="icon-title">{{ item.group }}</div>
                      <el-row
                        :gutter="0"
                        v-for="(rowItem, index) in item.iconList"
                        :key="index"
                      >
                        <el-col :span="4" v-for="(iconName, idx) in rowItem" :key="idx">
                          <el-tooltip
                            placement="bottom"
                            effect="light"
                            :show-after="1000"
                          >
                            <div
                              class="icon-card"
                              :style="
                                iconName === form.iconName
                                  ? 'background-color: #22C3AA;'
                                  : ''
                              "
                              @click="onSelectIcon(iconName)"
                            >
                              <el-icon
                                size="20px"
                                :color="
                                  iconName === form.iconName ? '#ffffff' : '#666666'
                                "
                              >
                                <component :is="iconName" />
                              </el-icon>
                            </div>
                            <template #content>
                              <span style="color: #666666">{{ iconName }}</span>
                            </template>
                          </el-tooltip>
                        </el-col>
                      </el-row>
                    </template>
                  </div>
                </el-scrollbar>
              </el-popover>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="权限路径" prop="url">
              <el-input v-model="form.url" class="form-input" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权重" prop="weight">
              <el-input-number
                class="form-input"
                v-model="form.weight"
                :min="0"
                :max="1000"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="颜色" prop="iconColor">
              <el-config-provider :locale="zhCn">
                <el-color-picker
                  v-model="form.iconColor"
                  color-format="hex"
                  :predefine="predefineColors"
                />
              </el-config-provider>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="启用" prop="enabled">
              <el-switch v-model="form.enabled" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="description">
          <el-input v-model="form.description" type="textarea" />
        </el-form-item>
      </el-form>
    </el-scrollbar>
  </el-dialog>
</template>

<style scoped lang="scss">
.icon-title {
  margin: 15px 0;
}

.icon-card {
  border: #f1f3f5 1px solid;
  width: 60px;
  height: 60px;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: all 0.4s;
}

.icon-card:hover {
  background-color: #f2f6fc;
}
</style>
